/******************************************************************************
 * Filename : prcom.c
 * Copyright: 
 * Created  : 2014-3-31 by franco.yin
 * Description -
 * 
 ******************************************************************************/

#include <string.h>
#include <stdlib.h>
#include <pthread.h>
#include <errno.h>
#include <signal.h>
#include <stdio.h>
#include <unistd.h>
#include <sys/shm.h>
#include "uc_prcom.h"

#define ucpmt_p(...)				printf(__VA_ARGS__)
	

void
ucpmt_sleep(int ms)
{
	struct timeval delay_time;
	int ret = 0;

	if (ms <= 0) return;
	
	delay_time.tv_sec = ms / 1000;
	delay_time.tv_usec = (ms % 1000)*1000;
	while(1) {
		ret = select(0, NULL, NULL, NULL, &delay_time);
		if(ret < 0 && errno == EINTR) {
			continue;
		}
		break;
	}
	return;
}

void
ucpmt_srv()
{
	void *pUCPrcom = NULL;
	ucprcom_av_fmt_s *pFmt = NULL;
	uint8_t *pData = NULL;
	int max_len = 0;
	int ret = 0;
	int cnt = 0;
	int n = 0;

	pUCPrcom = ucprcom_srv_creat(NULL, NULL);
	if(pUCPrcom == NULL) {
		ucpmt_p("creat error\n");
		return;
	}

	ucpmt_sleep(1000);

	ucpmt_p("start add data\n");
	while(1) {
		ret = ucprcom_srv_getp(pUCPrcom, UCPRCOM_DATA_TYPE_YUV, &pFmt, &pData, &max_len);
		if(ret != 0) {
			ucpmt_p("ucprcom_srv_getp error\n");
			break;
		}

		ucprcom_uptime(&pFmt->timestamp, NULL, 0);

		n = sprintf((char *)pData, "%d", cnt);
		cnt++;

		ucprcom_srv_putp(pUCPrcom, UCPRCOM_DATA_TYPE_YUV, 1, n + 1, 1);














		

		ret = ucprcom_srv_getp(pUCPrcom, UCPRCOM_DATA_TYPE_PCM, &pFmt, &pData, &max_len);
		if(ret != 0) {
			ucpmt_p("ucprcom_srv_getp error\n");
			break;
		}

		ucprcom_uptime(&pFmt->timestamp, NULL, 0);

		n = sprintf((char *)pData, "%d", cnt);
		cnt++;

		ucprcom_srv_putp(pUCPrcom, UCPRCOM_DATA_TYPE_PCM, 1, n + 1, 1);

		ucpmt_sleep(30);
	}
	
	ucpmt_p("srv exit\n");
}

void 
ucpmt_call_back(int type, ucprcom_av_fmt_s *pFmt, uint8_t *pData, int len, void *p)
{
	ucpmt_p("get data[%d][%d] type[%d] val[%d - %s]\n", (int)pFmt->timestamp.sec, (int)pFmt->timestamp.usec, type, len, (char *)pData);
}

void
ucpmt_cli()
{
	int ret = 0;

	ret = ucprcom_cli_creat();
	if(ret != 0) {
		ucpmt_p("ucprcom_cli_creat error\n");
		return;
	}
	ucprcom_cli_start(UCPRCOM_FLAG_PCM | UCPRCOM_FLAG_YUV, ucpmt_call_back, NULL);

	while(1) {
		ucpmt_sleep(3000);
	}
}

void
ucpmt_useage()
{
	ucpmt_p("\n./ucprcom -s\n");
	ucpmt_p("./ucprcom -c\n\n");
}

int 
main(int argc, char **argv) 
{
	if(argc != 2) {
		ucpmt_useage();
		return -1;
	}

	if(strcmp(argv[1], "-s") == 0) {
		ucpmt_srv();
	} else if(strcmp(argv[1], "-c") == 0) {
		ucpmt_cli();
	} else {
		ucpmt_useage();
	}

	return 0;
}

